import {defineStore} from 'pinia'
import {publicEncryptedData} from '@/utils/encrypted'
import router from '@/router'

export const useUserStore = defineStore('user-store', {
  state: () => {
    return {
      token: localStorage.getItem('X-token') || '',
      userInfo: {},
      role: null
    }
  },
  getters: {},
  actions: {
    setUserState(token) {
      this.token = token
      localStorage.setItem('X-token', token)
      this.userInfo = JSON.parse(publicEncryptedData(this.token, 'decrypt'))
      this.role = this.userInfo.type === 1 ? 'admin' : 'user'
    },
    getUserInfo() {
      const Xtoken = localStorage.getItem('X-token')
      if (Xtoken) {
        const decryptData = publicEncryptedData(Xtoken, 'decrypt')
        try {
          this.userInfo = JSON.parse(decryptData)
        }catch (e){
          this.userInfo = {}
        }
      }
      return this.userInfo
    },
    logout() {
      this.$patch({
        token: '',
        userInfo: {},
        role: null
      })
      localStorage.clear()
      router.replace({name: 'login'})
    }
  }
})
